package com.iiapk.gridnew;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.weibo.net.AsyncWeiboRunner;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;
import com.weibo.net.AsyncWeiboRunner.RequestListener;

public class ShareActivity extends Activity implements OnClickListener, RequestListener{
	private TextView mTextNum;
	private Button mSend;
	private EditText mEdit;
	private FrameLayout mPiclayout;
	private ImageView image;
	
	private String mPicPath = "";
	private String mContent = "";
	private String mAccessToken = "";
	private String mTokenSecret = "";
	
	public static final String EXTRA_WEIBO_CONTENT = "com.weibo.android.content";
	public static final String EXTRA_PIC_URI = "com.weibo.android.pic.uri";
	public static final String EXTRA_ACCESS_TOKEN = "com.weibo.android.accesstoken";
	public static final String EXTRA_TOKEN_SECRET = "com.weibo.android.token.secret";
	public static final int WEIBO_MAX_LENGTH = 140;
	
	public static final int NONE = 0;  
    public static final int PHOTOHRAPH = 1;// 拍照   
    public static final int PHOTOZOOM = 2; // 缩放   
    public static final int PHOTORESOULT = 3;// 结果   
    public static final String IMAGE_UNSPECIFIED = "image/*"; 
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.share_mblog_view);
		
		Intent in = this.getIntent();
		mPicPath = in.getStringExtra(EXTRA_PIC_URI);
		mContent = in.getStringExtra(EXTRA_WEIBO_CONTENT);
		mAccessToken = in.getStringExtra(EXTRA_ACCESS_TOKEN);
		mTokenSecret = in.getStringExtra(EXTRA_TOKEN_SECRET);
		
		AccessToken accessToken = new AccessToken(mAccessToken, mTokenSecret);
		Weibo weibo = Weibo.getInstance();
		weibo.setAccessToken(accessToken);
		
		Button close = (Button)this.findViewById(R.id.btnClose);
		close.setOnClickListener(this);
		mSend = (Button)this.findViewById(R.id.btnSend);
		mSend.setOnClickListener(this);
		LinearLayout total = (LinearLayout)this.findViewById(R.id.ll_text_limit_unit);
		total.setOnClickListener(this);
		mTextNum = (TextView)this.findViewById(R.id.tv_text_limit);
		ImageView picture = (ImageView)this.findViewById(R.id.ivDelPic);
		picture.setOnClickListener(this);
		image = (ImageView)this.findViewById(R.id.ivImage);
		
		mEdit = (EditText)this.findViewById(R.id.etEdit);
		mEdit.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,int count) {
				String mText = mEdit.getText().toString();
				int len = mText.length();
				if (len <= WEIBO_MAX_LENGTH) {
					len = WEIBO_MAX_LENGTH - len;
					mTextNum.setTextColor(R.color.text_num_gray);
					if (!mSend.isEnabled()) mSend.setEnabled(true);
				}
				else {
					len = len - WEIBO_MAX_LENGTH;

					mTextNum.setTextColor(Color.RED);
					if (mSend.isEnabled()) mSend.setEnabled(false);
				}
				mTextNum.setText(String.valueOf(len));
			}
		});
		mEdit.setText(mContent);
		mPiclayout = (FrameLayout)ShareActivity.this.findViewById(R.id.flPic);
		if(TextUtils.isEmpty(this.mPicPath)){
			mPiclayout.setVisibility(View.GONE);
		}else{
			mPiclayout.setVisibility(View.VISIBLE);
			File file = new File(mPicPath);
			if(file.exists()){
				Bitmap pic = BitmapFactory.decodeFile(this.mPicPath);
				//ImageView image = (ImageView)this.findViewById(R.id.ivImage);
				image.setImageBitmap(pic);
			}else{
				mPiclayout.setVisibility(View.GONE);
			}	
		}
		
		this.findViewById(R.id.btn_insert_topic).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				String _text = mEdit.getText().toString();
				_text+="#"+getText(R.string.weibo_btn_topic)+"#";
				mEdit.setText(_text);
			}
		});
		this.findViewById(R.id.btn_insert_at).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				String _text = mEdit.getText().toString();
				_text+="@"+getText(R.string.weibo_btn_at);
				mEdit.setText(_text);
			}
		});
		this.findViewById(R.id.btn_insert_pics).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				 Intent intent = new Intent(Intent.ACTION_PICK, null);  
                 intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);  
                 startActivityForResult(intent, PHOTORESOULT); 
			}
		});
		this.findViewById(R.id.btn_insert_pic).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));  
                 startActivityForResult(intent, PHOTOHRAPH); 
			}
		});
	}

	@Override
	public void onClick(View v) {
		int viewId = v.getId();
		switch(viewId){
		case R.id.btnClose:{
			finish();
			break;
		}
		case R.id.btnSend:{
			Weibo weibo = Weibo.getInstance();
			try {
				if(!TextUtils.isEmpty((String)(weibo.getAccessToken().getToken()))){
					mPicPath=mPicPath.replace("file://", "");
					if(!TextUtils.isEmpty(mPicPath)&&new File(mPicPath).exists()){
						upload(weibo, Weibo.APP_KEY, this.mPicPath, this.mContent, "", "");
					}else{
						update(weibo, Weibo.APP_KEY, mContent, "", "");						
					}
				}else{
					Toast.makeText(this, this.getString(R.string.please_login), Toast.LENGTH_LONG).show();
				}
			} catch (MalformedURLException e) {
				Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
			} catch (IOException e) {
				Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
			} catch (WeiboException e) {
				Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
			}catch(Exception e){
				Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
			}
			break;
		}
		case R.id.ll_text_limit_unit:{
			Dialog dialog = new AlertDialog.Builder(this)
			.setTitle(R.string.attention)
			.setMessage(R.string.delete_all)
			.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int which) {
							mEdit.setText("");
						}
					}).setNegativeButton(R.string.cancel, null)
			.create();
			dialog.show();
			break;
		}
		case R.id.ivDelPic:{
			Dialog dialog = new AlertDialog.Builder(this)
			.setTitle(R.string.attention)
			.setMessage(R.string.del_pic)
			.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int which) {
							mPiclayout.setVisibility(View.GONE);
						}
					}).setNegativeButton(R.string.cancel, null)
			.create();
			dialog.show();
			break;
		}
		default:
		}
	}

	
	private String upload(Weibo weibo, String source, String file, String status, String lon, String lat) 
		throws WeiboException{
			WeiboParameters bundle = new WeiboParameters();
			bundle.add("source", source);
			bundle.add("pic", file);
			bundle.add("status", status);
			if(!TextUtils.isEmpty(lon)){
				bundle.add("lon", lon);
			}
			if(!TextUtils.isEmpty(lat)){
				bundle.add("lat", lat);
			}
			String rlt = "";
			String  url = Weibo.SERVER + "statuses/upload.json";
			AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
			weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);
			
			return rlt;
	}

	private String update(Weibo weibo, String source, String status, String lon, String lat) 
		throws MalformedURLException, IOException, WeiboException{
			WeiboParameters bundle = new WeiboParameters();
			bundle.add("source", source);
			bundle.add("status", status);
			if(!TextUtils.isEmpty(lon)){
				bundle.add("lon", lon);
			}
			if(!TextUtils.isEmpty(lat)){
				bundle.add("lat", lat);
			}
			String rlt = "";
			String url = Weibo.SERVER + "statuses/update.json";
			AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
			weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);
			return rlt;
	}

	@Override
	public void onComplete(String response) {
		Toast.makeText(this, R.string.send_sucess, Toast.LENGTH_LONG).show();;	
		this.finish();
	}

	@Override
	public void onIOException(IOException e) {
		Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();;
	}

	@Override
	public void onError(WeiboException e) {
		Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();;
	}
	
	@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (resultCode == NONE)  
            return;  
        if (requestCode == PHOTOHRAPH) {  
            File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");  
            startPhotoZoom(Uri.fromFile(picture));  
        }  
        if (data == null)  
            return;  
        if (requestCode == PHOTOZOOM) {  
            startPhotoZoom(data.getData()); 
        }  
        if (requestCode == PHOTORESOULT) {  
            Bundle extras = data.getExtras();  
            mPiclayout.setVisibility(View.VISIBLE);
            if (extras != null) {  
                Bitmap photo = extras.getParcelable("data");  
                ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
                photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)压缩文件   
                image.setImageBitmap(photo);  
            }else{
            	image.setImageURI(data.getData());
            	mPicPath = data.getData().toString();
            }  
        }  
        super.onActivityResult(requestCode, resultCode, data);  
    }  
    
    public void startPhotoZoom(Uri uri) {  
        Intent intent = new Intent("com.android.camera.action.CROP");  
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);  
        intent.putExtra("crop", "true");  
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
        intent.putExtra("outputX", 64);  
        intent.putExtra("outputY", 64);  
        intent.putExtra("return-data", true);  
        startActivityForResult(intent, PHOTORESOULT);  
    }  
}
